package com.eddy.project.handler;

import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import javax.annotation.Resource;

/**
 * 编程式事务
 * 用法：
 * 获取当前事务，事务状态
 * TransactionStatus transactionStatus = transactionHandler.getTransactionStatus();
 *  //事务回滚
 * transactionHandler.rollback(transactionStatus);
 *  //事务提交
 * transactionHandler.commit(transactionStatus);
 *
 */
@Component
public class TransactionHandler {

    @Resource
    private PlatformTransactionManager platformTransactionManager;

    @Resource
    private TransactionDefinition transactionDefinition;


    /**
     * 获取当前事务，事务状态
     * @return
     */
    public TransactionStatus getCurrentTransactionStatus(){
        //事务平台管理器 通过事务定义器 获取到本地事务
        return platformTransactionManager.getTransaction(transactionDefinition);
    }


    /**
     * 事务回滚
     * @param transaction
     */
    public void rollback(TransactionStatus transaction){
        platformTransactionManager.rollback(transaction);
    }

    /**
     * 事务提交
     * @param transaction
     */
    public void commit(TransactionStatus transaction){
        platformTransactionManager.commit(transaction);
    }
}
